"""
    邮件工具类
   @author TinaRoot
   @since 2022/3/3 下午6:23
"""
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from aiapp.utils.redis_util import redisClient
from aiapp.utils.date_util import restOfDay
from aiapp import setting
import traceback

logger = setting.log_config.logger
application = setting.application


def statistics():
    """
        统计邮箱使用，限制发送频率，自动切换邮箱
    :return: bool
    """
    for u in application.MAIL_USER:
        key = application.MAIL_SEND_STATISTICS_KEY + u['mail_user']
        count = redisClient().get(key)

        if count and int(count) <= u['statistics']:
            return u
        elif count is None:
            return u
        else:
            logger.error(f"当前邮箱[{u['mail_user']}]已发送次数:{count}，超过设定中数量：{u['statistics']}")


def send_mail(receivers, subject, content):
    """
        发送普通邮件
        :param receivers接收人
        :param subject 标题
        :param content 内容
        :return: boolean
    """

    data = statistics()
    if data is None:
        return False
    MAIL_USER = data['mail_user']
    MAIL_PASS = data['mail_pass']

    # 邮件内容设置
    message = MIMEText(content, 'HTML')
    message['From'] = Header(MAIL_USER)
    message['To'] = Header(receivers)

    # 邮件标提
    message['Subject'] = Header(subject, 'utf-8')

    try:

        smtpObj = smtplib.SMTP()
        smtpObj.connect(application.MAIL_HOST, 587)
        smtpObj.login(MAIL_USER, MAIL_PASS)
        smtpObj.sendmail(MAIL_USER, receivers, message.as_string())
        smtpObj.quit()
        logger.debug("Success:邮件发送成功:SENDER {},To:{},subject:{},content:{}", MAIL_USER, receivers, subject,
                     content)
        incr = redisClient().incr(application.MAIL_SEND_STATISTICS_KEY + MAIL_USER)

        # 自增id小于2的时候说明有发送了，设置过期时间，今天剩下的秒数
        if int(incr) < 2:
            redisClient().expireTime(application.MAIL_SEND_STATISTICS_KEY + MAIL_USER, restOfDay())

        return True
    except smtplib.SMTPException:
        logger.error("Error:无法发送邮件:SENDER {},To:{},subject:{},content:{}", MAIL_USER, receivers, subject,
                     content
                     )
        traceback.print_exc()
        return False


def mailbox_template(title, other, content):
    """
    邮箱模板
    :param title: 标题
    :param content: 内容
    :param other: 其他
    :return: 字符串
    """
    temp = "<!DOCTYPE html>" \
           "<html lang='en' xmlns:th='http://www.thymeleaf.org' xmlns='http://www.w3.org/1999/xhtml'>" \
           "<head>" \
           "    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>" \
           "    <title> Email Tina!</title>" \
           "    <meta name='viewport' content='width=device-width, initial-scale=1.0'/>" \
           "    <link rel='icon' href='http://tool.tinaroot.cn/favicon.ico' class='md-opjjpmhoiojifppkkcdabiobhakljdgm_doc'>" \
           "    <style>" \
           "        table  td{" \
           "            text-align: center;" \
           "        }" \
           "    </style>" \
           "</head>" \
           "<body style='margin: 0; padding: 0;'>" \
           "" \
           "<table border='0' cellpadding='0' cellspacing='0' width='100%'>" \
           "    <tr>" \
           "        <td style='padding: 20px 0 30px 0;'>" \
           "            <table align='center' border='0' cellpadding='0' cellspacing='0' width='600'" \
           "                   style='border: 1px solid #cccccc;'>" \
           "                <tr>" \
           "                    <td align='center' bgcolor='#70bbd9'>" \
           "                        <img src='http://images.tinaroot.cn/D7TPzQ.jpg' alt='Creating Email Magic' width='100%'" \
           "                             style='display: block;'/>" \
           "                    </td>" \
           "                </tr>" \
           "                <tr>" \
           "                    <td bgcolor='#ffffff' style='padding: 40px 30px 40px 30px;'>" \
           "                        <table border='0' cellpadding='0' cellspacing='0' width='100%'>" \
           "                            <tr>" \
           "                                <td style='color: #153643; font-family: Arial, sans-serif; font-size: 24px;'>" \
           "                                    <b>" + title + \
           "</b>" \
           "                                </td>" \
           "                            </tr>" \
           "                            <tr>" \
           "                                <td style='padding: 20px 0 30px 0;'>" \
           "                                </td>" \
           "                            </tr>" \
           "                            <tr>" \
           "                                <td>" \
           "                                    <table border='0' align='center' cellpadding='0' cellspacing='0' width='100%'>" \
           "                                        <tr>" \
           "                                            <td style='font-size: 0; line-height: 0;' width='20%'>" \
           "                                                &nbsp;" \
           "                                            </td>" \
           "                                            <td width='352' valign='top'>" \
           "                                                <table border='0' cellpadding='0' cellspacing='0' width='100%'>" \
           + other + content + \
           "                                                </table>" \
           "                                            </td>" \
           "                                            <td style='font-size: 0; line-height: 0;' width='20%'>" \
           "                                                &nbsp;" \
           "                                            </td>" \
           "                                        </tr>" \
           "                                    </table>" \
           "                                </td>" \
           "                            </tr>" \
           "                        </table>" \
           "                    </td>" \
           "                </tr>" \
           "                <tr>" \
           "                    <td bgcolor='#e1e1e1' style='padding: 10px 10px 10px 10px;'>" \
           "                        <table border='0' cellpadding='0' cellspacing='0' width='100%'>" \
           "                            <tr>" \
           "                                <td style='color: #555; font-family: Arial, sans-serif; font-size: 14px;'>" \
           "                                    Copyright © 2020.Company TinaRoot.CN All<br/>" \
           "                                </td>" \
           "                                <td align='right'>" \
           "                                    <table border='0' cellpadding='0' cellspacing='0'>" \
           "                                        <tr>" \
           "                                            <td>" \
           "                                                <a href='http://tinaroot.cn'>" \
           "                                                    <img src='http://images.tinaroot.cn/user.jpg' alt='tinaroot.cn'" \
           "                                                         width='38' height='38'" \
           "                                                         style='display: block;border-radius: 500rem;' border='0'/>" \
           "                                                </a>" \
           "                                            </td>" \
           "                                            <td style='font-size: 0; line-height: 0;' width='20'>&nbsp;</td>" \
           "                                        </tr>" \
           "                                    </table>" \
           "                                </td>" \
           "                            </tr>" \
           "                        </table>" \
           "                    </td>" \
           "                </tr>" \
           "            </table>" \
           "        </td>" \
           "    </tr>" \
           "</table>" \
           "</body>" \
           "</html>"

    return temp


def send_verification_code(to, subject, title, code):
    """
        发送验证码
    :param to:  收件人
    :param subject: 标题
    :param code: 验证码
    :param title: 内容标题
    :return: bool
    """
    flag = send_mail(to, subject, mailbox_template(title, "", code))
    if flag:
        redisClient().set(application.MAIL_VERIFICATION_CODE_KEY + to, code, application.MAIL_VERIFICATION_CODE_EXPIRED_KEY)
    return flag


if __name__ == '__main__':
    print('可用邮箱', statistics())
